﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Emit;
using System.Text;
using YAPL.Language.Core.Types;

namespace YAPL.Language.Compiler.CodeGen.ReflectionEmitGenerator.AstGen {
	public class ReWhileGenerator : ReExpressionGenerator {
		public ReWhileGenerator(ReCodeGenerator generator) : base(generator) {}
		public override void Generate(Ast.Expression expr) {

			var whileExpr = (Ast.WhileExpression)expr;
			var ilGen = Generator.Get<ILGenerator>(ReCodeGenerator.IL_GENERATOR_KEY);
			var beforeLabel = ilGen.DefineLabel();
			ilGen.MarkLabel(beforeLabel);

			Generator.EmitExpression(whileExpr.Condition);

			ilGen.Emit(OpCodes.Castclass, typeof(YAPLBoolean));
			var boolGetter = typeof(YAPLBoolean).GetProperty("BoolValue").GetGetMethod();
			ilGen.Emit(OpCodes.Callvirt, boolGetter);

			var afterLabel = ilGen.DefineLabel();
			ilGen.Emit(OpCodes.Brfalse, afterLabel);

			Generator.EmitExpression(whileExpr.Body);
			ilGen.Emit(OpCodes.Br, beforeLabel);
			

			ilGen.MarkLabel(afterLabel);

			ilGen.Emit(OpCodes.Ldnull); //TODO Change to something meaningful
		}
	}
}
